package com.chromatic.competition.view.profile;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.chromatic.competition.R;
import com.chromatic.competition.model.UserInformation;
import com.chromatic.competition.utils.UserManager;
import com.chromatic.competition.utils.UserLoginStatus;
import com.chromatic.competition.view.account.LoginActivity;

import org.json.JSONException;
import org.json.JSONObject;

public class ProfileFragment extends Fragment {
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_profile, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        UserLoginStatus userLoginStatus = new UserLoginStatus(requireContext());

        TextView profileUsernameTextView = view.findViewById(R.id.profile_name);
        TextView profileEmailTextView = view.findViewById(R.id.profile_email);
        TextView profileSchoolTextView = view.findViewById(R.id.profile_school);
        TextView profileLevelTextView = view.findViewById(R.id.profile_level);

        Button editProfileButton = view.findViewById(R.id.edit_profile_button);
        View accountModule = view.findViewById(R.id.account_module);
        View resumeModule = view.findViewById(R.id.resume_module);
        View postModule = view.findViewById(R.id.my_posts_module);
        View walletModule =view.findViewById(R.id.wallet_module);
        View logoutModule = view.findViewById(R.id.logout_module);
        View settingsModule = view.findViewById(R.id.settings_module);

        // 设置用户username和email
        SharedPreferences prefs = requireActivity().getSharedPreferences("login_info", Context.MODE_PRIVATE);
        String userJson = prefs.getString("user", "");
//        Log.d("ProfileFragment", "彩旗账户信息: " + userJson);

        if (!userJson.isEmpty()) {
            try {
                JSONObject userObject = new JSONObject(userJson);
//                String username = userObject.getString("username");
                String email = userObject.getString("email");
                boolean isAdmin = Boolean.parseBoolean(userObject.getString("admin"));
                // 将提取出的用户名和电子邮件设置到对应的TextView
                profileEmailTextView.setText(email);
                if(isAdmin)  profileLevelTextView.setText("管理员");
                else profileLevelTextView.setText("普通用户");

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        int userId = userLoginStatus.getCurrentUserId();
        UserManager.getUserInformation(userId, new UserManager.UserInformationCallback() {
            @Override
            public void onSuccess(UserInformation userInformation) {
                String nickname = userInformation.getNickname();
                String university = userInformation.getUniversity();
                profileUsernameTextView.setText(nickname);
                profileSchoolTextView.setText(university);
                // 在此处使用nickname和university进行其他操作
            }
            @Override
            public void onError(String errorMessage) {
                // 处理错误情况
                Toast.makeText(getContext(), "读取昵称和学校出错：" + errorMessage, Toast.LENGTH_SHORT).show();
            }
        });
        
        editProfileButton.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(),MyUserInfoActivity.class);
            startActivity(intent);
        });

        accountModule.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), MyAccountActivity.class);
            startActivity(intent);
        });

        resumeModule.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), ResumeActivity.class);
            startActivity(intent);
        });

        postModule.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), MyPostActivity.class);
            startActivity(intent);
        });

        walletModule.setOnClickListener(v -> {
            // 跳转到 LoginActivity
            Intent intent = new Intent(getActivity(), MyWalletActivity.class);
            startActivity(intent);
        });

        settingsModule.setOnClickListener(v -> {
            // 跳转到 LoginActivity
            Intent intent = new Intent(getActivity(), SettingsActivity.class);
            startActivity(intent);
        });

        logoutModule.setOnClickListener(v -> {
            // 清除 SharedPreferences 中的数据
            SharedPreferences sharedPreferences = requireActivity().getSharedPreferences("login_info", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.clear();
            editor.apply();

            // 跳转到 LoginActivity
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);

            // 如果你希望清除所有的后台活动并让 LoginActivity 成为新的栈顶，可以添加以下两行
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            requireActivity().finish();
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}